import React, { useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import { ProList } from '@ant-design/pro-components';
import { Avatar, Button, Card, Col, List, Row, Tag } from 'antd';
import DictSelect from '@/components/DictSelect';
import EditForm from '@/components/EditForm';
import { loadLanguage } from '@uiw/codemirror-extensions-langs';
import { handleAdd, handleUpdate } from './action';
import CodeMirror from '@uiw/react-codemirror';
import type { TemplateItem } from '@/services/develop/types';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { ProFormRadio, ProFormText } from '@ant-design/pro-form';
import { listTemplate } from '@/services/develop/template';
import type { LabeledValue } from 'antd/lib/select';

type TemplateProperty = {
  schemaId: string;
};

const Template: React.FC<TemplateProperty> = (props) => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<TemplateItem>();
  const [templateContent, setTemplateContent] = useState<string>();
  const [language, setLanguage] = useState<string>('java');

  return (
    <>
      <ProList<any>
        ghost={false}
        actionRef={actionRef}
        pagination={false}
        // dataSource={data}
        grid={{ gutter: 16, column: 4 }}
        rowSelection={false}
        request={listTemplate}
        params={{ templateSchemaId: props.schemaId }}
        toolBarRender={() => {
          return [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrentRow(undefined);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新增
            </Button>,
          ];
        }}
        renderItem={(item, index) => {
          if (item && item.id) {
            return (
              <List.Item key={item.id}>
                <Card
                  hoverable
                  // className={styles.card}
                  // style={{
                  //   backgroundColor: '#f0f2f5',
                  // }}
                  actions={[
                    <a
                      key="option1"
                      onClick={() => {
                        setCurrentRow(item);
                        setTemplateContent(item.template);
                        handleModalVisible(true);
                      }}
                    >
                      <EditOutlined />
                      &nbsp;&nbsp;编辑
                    </a>,
                    <a key="option2">
                      <DeleteOutlined />
                      &nbsp;&nbsp;删除
                    </a>,
                  ]}
                >
                  <Card.Meta
                    avatar={
                      <Avatar
                        size={32}
                        style={{ backgroundColor: 'var(--ant-primary-color)', color: '#fff' }}
                      >
                        {item.type.charAt(0).toUpperCase() + item.type.slice(1)}
                      </Avatar>
                    }
                    title={item.name}
                    description={
                      <Row
                        style={{
                          marginTop: '18px',
                        }}
                      >
                        <Col>
                          模板引擎：
                          <Tag
                            color="warning"
                            style={{
                              marginBottom: '18px',
                            }}
                          >
                            {
                              {
                                freemarker: 'Freemarker',
                                beetl: 'Beetl',
                                velocity: 'Velocity',
                              }[item.engine]
                            }
                          </Tag>
                        </Col>
                        <Col>
                          创建时间：
                          <Tag color="warning">{item.createTime}</Tag>
                        </Col>
                      </Row>
                    }
                  />
                </Card>
              </List.Item>
            );
          }
          return (
            <List.Item>
              <Button type="dashed">
                <PlusOutlined /> 新增
              </Button>
            </List.Item>
          );
        }}
      />

      <EditForm
        visible={createModalVisible}
        name="模版"
        width={1440}
        model={currentRow || { id: undefined }}
        onAdd={(values) =>
          handleAdd({
            ...values,
            template: templateContent,
          })
        }
        onUpdate={(values) =>
          handleUpdate({
            ...values,
            template: templateContent,
          })
        }
        afterEdit={() => {
          setCurrentRow(undefined);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={(visible) => {
          handleModalVisible(visible);
          if (!visible) {
            setTemplateContent(undefined);
          }
        }}
      >
        <ProFormText name="id" hidden={true} />
        <ProFormText name="templateSchemaId" initialValue={props.schemaId} hidden={true} />
        <ProFormText required label="模板名称" name="name" colProps={{ span: 6 }} />
        <ProFormText required label="模板编码" name="code" colProps={{ span: 6 }} />
        <DictSelect
          label="编程语言"
          name="type"
          cols={6}
          dict="language.programe"
          fieldProps={{
            onSelect: (value: string | number | LabeledValue) => setLanguage(value.toString()),
          }}
        />
        <DictSelect label="模板引擎" name="engine" cols={6} dict="template.engine" />
        <ProFormText
          label="根路径"
          name="rootPath"
          tooltip="模板生成文件存放的根路径，如/${project.name}/${project.name}-api，当工程名为szhome-system时，生成的文件根目录存放在/szhome-system/szhome-system-api目录下"
          colProps={{ span: 6 }}
        />
        <ProFormText
          label="父路径"
          name="parentPath"
          tooltip="模板生成文件存放的父路径，如${model.module}，当模型所属模块为system时，生成的文件父目录为/system"
          colProps={{ span: 6 }}
        />
        <ProFormText
          required
          label="文件名"
          name="file"
          placeholder={'支持模板表达式，如${model.name?cap_first}Service.java'}
          colProps={{ span: 6 }}
        />
        <ProFormRadio.Group
          name="fileType"
          label="文件类型"
          tooltip="决定模版生成文件的父路径存放位置，源码文件放置在 src/main/java 目录，资源文件则放置在 src/main/resource 目录，非工程文件将直接放置输出路径中"
          fieldProps={{
            defaultValue: 'source',
          }}
          colProps={{ span: 6 }}
          options={[
            {
              label: '源码文件',
              value: 'source',
            },
            {
              label: '资源文件',
              value: 'resource',
            },
            {
              label: '其它文件',
              value: 'other',
            },
          ]}
        />
        <Col span={24}>
          <CodeMirror
            value={templateContent}
            height="800px"
            width="100"
            theme={'dark'}
            onChange={setTemplateContent}
            placeholder={'请输入您的模板代码...'}
            extensions={[loadLanguage(language)]}
          />
        </Col>
      </EditForm>
    </>
  );
};

export default Template;
